if(typeof G == "undefined") {
    var G = {};
}

if(typeof G.cust == "undefined") {
    G.cust = {};
}


G.cust = {

    //会员信息
    cust_id: E.getCookie("WANSONSHOP_IDENTIFIER"),

    //设置会员cookie
    set_cookie: function( c ) {
        E.setCookie("WANSONSHOP_IDENTIFIER", c, 604800, G.args.cookie_domain);
        E.setCookie("REMEMBER_USERNAME", c, 2592000, G.args.cookie_domain);
        this.cust_id = c;
    },

    //显示欢迎项
    show_IDENTIFIER: function( id ) {
        var html = "";
        if (this.cust_id == null) {
            var rem_user = E.getCookie('REMEMBER_USERNAME');
            if (rem_user) {
                html ="欢迎您 " + rem_user + ",请先 [ <a href=\"" + G.args.login + "\">登录</a> ] [ <a href=\"" + G.args.register + "\">注册</a> ]";
            } else {
                html ="欢迎,请先 [ <a href=\"" + G.args.login + "\">登录</a> ] [ <a href=\"" + G.args.register + "\">注册</a> ]";
            }
        } else {
            html ="欢迎您 " + this.cust_id + "，[ <a href=\"" + G.args.logout + "\">退出</a> ]";
        }
        $("#" + id).html(html);
    },

    error: {
        e1: '请输入手机号码',
        e2: '该手机号码名已被使用 请  <a href="' + G.args.login + '">登录</a>  或  <a href="' + G.args.getpwd + '">找回密码</a>',
        e3: "请输入密码",
        e4: "密码必须是6-30位字符，可使用字母、数字或符号的组合",
        e5: "您两次输入的密码不一致",
        e6: "验证码不正确，请重新输入",
        e7: "请输入验证码"
    },

    //客户登录
    login: function( id ) {

        $("#log_content").find(".login_error").text("");

        var dt = E.getFormValues(id);

        var error_arr = {},
            error_flg = false;

        if (!E.isMobile(dt.loginName))
            error_arr['loginName'] = this.error.e1;

        if (E.empty(dt.loginPwd))
            error_arr['loginPwd'] = this.error.e3;

        $.each(error_arr,function(k, v) {
            $("#" + k + "Error").text(v).removeClass("hide");
            error_flg = true;
        });
		
        if (!error_flg) {
            E.loadding.open("正在登录，请稍候...");
            this.act = "login";
            E.ajax_post({
                action: 'customer',
                operFlg: 2,
                data: dt,
                call: "G.cust.result"
            });
        }

    },


    //用户注册
    register: function( id ) {

        var dt = E.getFormValues(id);

        var error_arr = {},
            error_flg = false;

        if (!E.isMobile(dt.regName))
            error_arr['regName'] = this.error.e1;

        if (!E.isPwd(dt.regPwd))
            error_arr['regPwd'] = this.error.e4;
        else if (dt.regPwd != dt.regPwd2)
            error_arr['regPwd2'] = this.error.e5;

        if (E.empty(dt.regYzm) && dt.regYzm != 2)
            error_arr['regYzm'] = this.error.e6;

        $.each(error_arr,function(k,v) {
            $("#" + k + "Error").text(v).removeClass("hide");
            error_flg = true;
        });


        if (!error_flg) {
            E.loadding.open("正在注册，请稍候...");
            this.act = "reg";
            E.ajax_post({
                action: 'customer',
                operFlg: 1,
                data: dt,
                call: "G.cust.result"
            });

        }

    },

    result: function( o ) {
        E.loadding.close();
        if (o.code == 200) {
            this.set_cookie(o.data);
            self.location = this.referer_url;
        } else {
            $("#" + this.act + "Yzm").val("");
            E.captcha("yzm_img", 2);
            $("#" + o.field + "Error").text(o.message).show();
        }
    },


    change: function(o, flg) {
        $("#p_customer").find("h3").find("span").removeClass("current").eq($(o).index()).addClass("current");
        if (flg == 1) {
            $("#p_login").removeClass("hide");
            $("#p_reg").addClass("hide");
            E.captcha('login_yzm_img');
        } else {
            $("#p_reg").removeClass("hide");
            $("#p_login").addClass("hide");
            E.captcha('reg_yzm_img');
        }
    },

    close: function() {
        $("#p_customer").addClass("hide");
    },

    open: function() {
        $("#p_customer").removeClass("hide");
        $("#p_customer").find("h3").find("span").removeClass("current").eq(0).addClass("current");
        $("#p_login").removeClass("hide");
        $("#p_reg").addClass("hide");
        E.captcha('login_yzm_img');
    }

};


if(typeof G.cart == "undefined") {
    G.cart = {};
}

G.cart.general = {

    openFlg: 2,

    //添加商品到购物车
    add: function( postID, goods_amount ) {
        E.loadding.open("正在购买商品，请稍候...");
        this.openFlg = 2;
        E.ajax_post({
            action: "cart",
            operFlg: this.openFlg,
            data: {
                postID: postID,
                goods_amount: goods_amount
            },
            call: "G.cart.general.result"
        });
    },

    //立即购买
    buy: function( postID, goods_amount ) {
        E.loadding.open("正在购买商品，请稍候...");
        this.openFlg = 10;
        E.ajax_post({
            action: "cart",
            operFlg: this.openFlg,
            data: {
                postID: postID,
                goods_amount: goods_amount
            },
            call: "G.cart.general.result"
        });
    },

    result: function(o) {
        if (o.code == 200) {
            if (this.openFlg == 2) {
                self.location = G.args.cart + '?emt=0.0.3.16.0.6';
            } else {
                self.location = G.args.nowbuy + '?emt=0.0.3.16.0.7';
            }
        } else {
            E.loadding.close();
            E.alert(o.message);
        }
    }

};


G.search = {

    opp: $("#search"),

    defaultKey: "输入你想要查找的商品",

    clear: function() {
        if (this.opp.val() == this.defaultKey) {
            this.opp.val("");
        }
    },

    set: function() {
        if(this.opp.val()==""){
            this.opp.val(this.defaultKey);
        }
    },

    start: function() {
        var keyword = E.trim(this.opp.val());
        if (keyword == "" || keyword == this.defaultKey)
            this.opp.val(this.defaultKey);
        else {
            self.location = '/wap/search-' + encodeURI(keyword) + '-sale-desc-1.html';
        }
    }

}

//商品收藏
G.favorites = {
	
	//删除商品收藏
	del: function( postID, pcustID ) {
		E.loadding.open();
		E.ajax_get({
            action:"goods",
            operFlg:7,
            data:{
                postID:postID,
                pcustID:pcustID
            },
            call:"G.favorites.delResult"
        });
	},
	
	//商品收藏操作返回值
	delResult: function( o ) {
		E.loadding.close();
		if (o.code == 200) {
            E.alert("删除成功", 2);
            setInterval("self.location='/wap/member_favorites.html'",500);
        } else {
            E.alert(o.message);
        }
	}
};


var GC_img_preload_gap = 500;
var GC_delay_todoload = 100;

var GF_img_index1 = true;
var GF_do_loading = false;
var GV_loadimg_handler = 0;
var GV_lazytype = 0;
var GV_img_indexs1 = new Array();
var GV_img_indexs2 = new Array();
var GV_img_loading = new Array();

function create_imgItem(index,top,bottom){
    var o = new Object();
    o.index = index;
    o.top = top;
    o.bottom = bottom;
    return o;
}

function get_visionBottom(){
    var t, h;
    t = document.documentElement.scrollTop || document.body.scrollTop;
    h = document.documentElement.clientHeight || document.body.clientHeight;
    return t + h;
}


function get_targetTop(p){
    var t = 0;
    while(p){
        if (p.offsetTop == undefined){
            return t;
        }
        t += p.offsetTop;
        p = p.offsetParent;
    }
    return t;
}

function do_loadimg(){
    if (GV_img_loading.length == 0){
        GF_do_loading = false;
        return false;
    }

    var vision_top = 0;
    var vision_bottom = 0;

    if (GV_lazytype == 1){
        vision_top = document.documentElement.scrollTop || document.body.scrollTop;
        vision_bottom = get_visionBottom();
    }

    var img_count = GV_img_loading.length;
    var img_tmp = null;
    for (var i=0;i<img_count;i++){
        img_tmp = document.getElementById(GV_img_loading[i]);
        if (img_tmp == null)
            continue;
        if (img_tmp.getAttribute("orginalsrc") != null)
            img_tmp.src = img_tmp.getAttribute("orginalsrc");
        else if (img_tmp.getAttribute("lazycall") != null)
            eval(img_tmp.getAttribute("lazycall"));
    }
    GV_img_loading.length = 0;
    GF_do_loading = false;
    return true;
}

function start_loadimg(){
    GF_do_loading = true;
    if (GV_lazytype == 0){
        GV_loadimg_handler = setTimeout("do_loadimg();",GC_delay_todoload);
    }else{
        do_loadimg();
    }
}

function clear_lazyloadimg(){
    if (GV_loadimg_handler > 0){
        clearTimeout(GV_loadimg_handler);
        GV_loadimg_handler = 0;
    }
}


function check_scroll(event){
    if (GF_do_loading){
        if (GV_lazytype == 0)
            clear_lazyloadimg();
        else
            return false;
    }

    var img_count = 0;
    var img_top = 0;
    var img_bottom = 0;
    var img_tmp = null;
    var loaded = false;

    var vision_top = document.documentElement.scrollTop || document.body.scrollTop;
    var vision_bottom = get_visionBottom();
    if (GF_img_index1){
        img_count = GV_img_indexs1.length;
        for (var i=0; i < img_count; i++){
            if (GV_lazytype == 0){
                img_top = GV_img_indexs1[i].top;
                img_bottom = GV_img_indexs1[i].bottom;
                loaded = img_top - vision_bottom <= GC_img_preload_gap && img_bottom > vision_top;
            }else{
                img_tmp = document.images[GV_img_indexs1[i].index];
                img_top = get_targetTop(img_tmp);
                loaded = img_top - vision_bottom <= GC_img_preload_gap;
            }
            if (loaded)
                GV_img_loading.push(GV_img_indexs1[i].index);
            else
                GV_img_indexs2.push(GV_img_indexs1[i]);
        }
        GV_img_indexs1.length = 0;
    }else{
        img_count = GV_img_indexs2.length;
        for (var i=0; i < img_count; i++){
            if (GV_lazytype == 0){
                img_top = GV_img_indexs2[i].top;
                img_bottom = GV_img_indexs2[i].bottom;
                loaded = img_top - vision_bottom <= GC_img_preload_gap && img_bottom > vision_top;
            }else{
                img_tmp = document.images[GV_img_indexs2[i].index];
                img_top = get_targetTop(img_tmp);
                loaded = img_top - vision_bottom <= GC_img_preload_gap;
            }
            if (loaded)
                GV_img_loading.push(GV_img_indexs2[i].index);
            else
                GV_img_indexs1.push(GV_img_indexs2[i]);
        }
        GV_img_indexs2.length = 0;
    }

    GF_img_index1 = !GF_img_index1;
    if (GV_img_loading.length > 0){
        start_loadimg();
    }
}

function wanson_init_lazy(){
    var img_count = document.images.length;
    if (img_count == 0)
        return false;

    var vision_top = document.documentElement.scrollTop || document.body.scrollTop;
    var vision_bottom = get_visionBottom();
    var img_top = 0;
    var img_bottom = 0;
    var img_tmp = null;
    for (var i=0;i<img_count;i++){
        img_tmp = document.images[i];
        if (img_tmp == undefined)
            continue;
        if (img_tmp.getAttribute("orginalsrc") == null && img_tmp.getAttribute("lazycall") == null)
            continue;

        img_top = get_targetTop(img_tmp);
        img_bottom = img_top + img_tmp.offsetHeight;

        img_tmp.id = (((1+Math.random())*0x10000)|0).toString(16).substring(1)+
            (((1+Math.random())*0x10000)|0).toString(16).substring(1)+
            (((1+Math.random())*0x10000)|0).toString(16).substring(1)+
            (((1+Math.random())*0x10000)|0).toString(16).substring(1)+
            (((1+Math.random())*0x10000)|0).toString(16).substring(1)+
            (((1+Math.random())*0x10000)|0).toString(16).substring(1)+
            (((1+Math.random())*0x10000)|0).toString(16).substring(1)+
            (((1+Math.random())*0x10000)|0).toString(16).substring(1);
        if (img_top - vision_bottom <= GC_img_preload_gap && img_bottom > vision_top)
            GV_img_loading.push(img_tmp.id);
        else{
            GV_img_indexs1.push(create_imgItem(img_tmp.id,img_top,img_bottom));
        }
    }
    if (GV_img_loading.length == 0 && GV_img_indexs1.length == 0)
        return false;

    if (window.attachEvent){
        window.attachEvent("onscroll", check_scroll, false);
    }else{
        window.addEventListener("scroll", check_scroll, false);
    }
    window.onresize = check_scroll;

    if (GV_img_loading.length > 0){
        start_loadimg();
    }

    return true;
}


function init_lazy(){
    GV_lazytype = 0;
    setTimeout("wanson_init_lazy();",100);
}

function init_dynamic_lazy(){
    GV_lazytype = 1;
    setTimeout("wanson_init_lazy();",100);
}

/***************导航收起 下拉效果********************/
$(function(){
    $('.wine_center').mouseenter(function(){
        $(this).find('.drop_list').addClass('drop_show');

    }).mouseleave(function(){
            $(this).find('.drop_list').removeClass('drop_show');

        });
});
/***********排序方式*************/
$(function(){
    $('.category_t ul li').click(function(){
        $(this).addClass('Em_t_a').siblings().removeClass('Em_t_a');
    });
});

/************************/
$(function(){
    $('.nav_tag dl').mouseenter(function(){
        $(this).addClass('dl_bg');
        $(this).find('.dd_s').addClass('w');
    }).mouseleave(function(){
            $(this).removeClass('dl_bg');
            $(this).find('.dd_s').removeClass('w');
        });

});

/*****************右侧浮动************************/
$(function(){
    $('.RightScrollContainer .minusNum').click(function(){
        $('.RightScrollBox').hide(500);
        $(this).css('display','none');
        $('.RightScrollContainer .plusNum').css('display','block');
    });
    $('.RightScrollContainer .plusNum').click(function(){
        $('.RightScrollBox').show(500);
        $(this).css('display','none');
        $('.RightScrollContainer .minusNum').css('display','block');
    });
});


//购物车
$('#cartBoxList').mouseenter(function(){
    $('#cartMain').addClass('cart_show');
    E.ajax_get({ action: "cart", operFlg: 1, call: "displayMinCart"});

}).mouseleave(function(){
        $('#cartMain').removeClass('cart_show');
    });

//购物车展示
function displayMinCart( result ) {
    var listHtml = ''; //购物车html内容
    var goodsTotalNum = 0; //商品总数量
    var goodsTotalPrice = 0; //商品总价格
    var goodsName = ''; //商品名称
    var goodsImgLink = ''; //商品图片链接
    var goodsLink = ''; //商品链接
    if ( result.code == 200 ) {

        listHtml += '<div class="c_p_list" id="cartProList">';
        $.each(result.data, function(k,v){
            goodsTotalNum += parseInt(v.amount);
            goodsTotalPrice += parseFloat(v.price) * parseInt(v.amount);
            goodsName = v.name;
            goodsImgLink = v.img_link;
            goodsLink = v.link;
            listHtml += '<div class="sub_shop">';
            listHtml += '<div class="sub_img">';
            listHtml += '<a href="'+goodsLink+'"  target="_blank" title="">';
            listHtml += '<img src="'+goodsImgLink+'" width="50" height="50">';
            listHtml += '</a>';
            listHtml += '</div>';
            listHtml += '<div class="sub_info">';
            listHtml += '<p class="sub_info_name">';
            listHtml += '<a href="'+goodsLink+'"  target="_blank" title="">'+goodsName+'</a>';
            listHtml += '</p>';
            listHtml += '<p>';
            listHtml += '<span style="color:#ED1C24;">￥'+v.price.toFixed(2)+'</span> x  '+v.amount+'';
            listHtml += '</p>';
            listHtml += '</div>';
            listHtml += '</div>';
        });
        listHtml += '</div>';
        listHtml += '<div class="c_number">';
        listHtml += '<p class="p1">';
        listHtml += '<span class="p1_l">共<strong style="font-weight:normal;">'+goodsTotalNum+'</strong>件商品</span>';
        listHtml += '<span class="p1_r">总计金额：<strong style="font-size:16px;font-weight:normal;">￥'+goodsTotalPrice.toFixed(2)+'</strong></span>';
        listHtml += '</p>';
        listHtml += '<p class="p2"><a href="' + G.args.cart + '" class="go_checkout">去购物车结算</a></p>	';
        listHtml += '</div>';
    } else {
        listHtml += result.message;
    }
    $('#cartMain').html(listHtml).addClass('cart_show');
}

$(function(){
    //点击头部右侧下拉
    $('.wap_header .house').on('click',function(){

        if($('.topBigCate').css("display") == "none"){
            $('.topBigCate').show();
        }else{
            $('.topBigCate').hide();
        }
    });

    //左侧浮动左移显示 隐藏
    $('.bar_pic').click(function(){
        if($(this).hasClass('bar_pic_cl')){
            $(this).removeClass('bar_pic_cl');
            $(this).parent().animate({left:"-60px"},100);

        }else{
            $(this).addClass('bar_pic_cl');
            $(this).parent().animate({left:"0"},100);
        }

    });

	
	//返回顶部
	$('.footer_box a.backtop').click(function(){
		$('body,html').animate({scrollTop:0},100);
	});	
});
